package top.drinyeit.weilong.presenter;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import java.util.List;
import java.util.Map;

import top.drinyeit.weilong.activity.CommodityDetailActivity;
import top.drinyeit.weilong.activity.CommodityDetailNewActivity;
import top.drinyeit.weilong.activity.ShopSearchActivity;
import top.drinyeit.weilong.adapter.CategoryAdapter;
import top.drinyeit.weilong.model.CategoryGoodsDetailsBean;
import top.drinyeit.weilong.retrofit.HttpResponse;
import top.drinyeit.weilong.retrofit.RetrofitMethod;
import top.drinyeit.weilong.retrofit.subscriber.CommonSubscriber;
import top.drinyeit.weilong.retrofit.subscriber.SubscriberListener;

import static top.drinyeit.weilong.app.Constant.COMMON_SUCCESS;

/**
 * Created by Administrator on 2018/2/6.
 */

public class ShopSearchPresenter {
    private ShopSearchActivity activity;
    private CategoryAdapter categoryAdapter;
    public ShopSearchPresenter(ShopSearchActivity activity){
        this.activity = activity;
    }

    //店铺内搜索结果
    public void shopSearch(final Map<String, Object> map) {
        CommonSubscriber<HttpResponse<List<CategoryGoodsDetailsBean>>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<List<CategoryGoodsDetailsBean>>>() {
            @Override
            public void onError(String e, int code) {
                activity.dismissLoading();
                activity.showToastMsg("错误，请重新操作！");
                activity.searchKey.setFocusable(true);

            }

            @Override
            public void onNext(HttpResponse<List<CategoryGoodsDetailsBean>> o) {
                activity.dismissLoading();
                if (o.getCode() == COMMON_SUCCESS) {
                    categoryAdapter = new CategoryAdapter(o.getData(),null);
                    activity.mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
                    activity.mRecyclerView.setAdapter(categoryAdapter);
                    if (categoryAdapter != null && categoryAdapter.getData().size() > 0){
                        categoryAdapter.setOnItemClickListener(new CategoryAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, final int position) {
                                Intent intent = new Intent(activity, CommodityDetailNewActivity.class);
                                intent.putExtra("id", categoryAdapter.getData().get(position).getId());
                                activity.startActivityForResult(intent, 1);
                            }
                        });
                    }
                } else {
                    activity.showToastMsg(o.getMessage());
                }
                activity.searchKey.setFocusable(true);
            }
        });
        RetrofitMethod.getInstance().shopSearch(subscriber, map);
    }
}
